/**
* Copyright (c) 2007, Regents of the University of Colorado
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the University of Colorado at Boulder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package jubilee.treebank;
import jubilee.util.*;

/**
 * TBReader reads a Treebank file, and returns each tree as TBTree format.
 * For example, here is the output generated by the following code.
 * <pre>
 * "wsj_0001.mrg":
 * ( (S 
 *   (NP-SBJ 
 *    (NP (NNP Pierre) (NNP Vinken) )
 *    (, ,) 
 *    (ADJP 
 *      (NP (CD 61) (NNS years) )
 *      (JJ old) )
 *    (, ,) )
 *  (VP (MD will) 
 *    (VP (VB join) 
 *      (NP (DT the) (NN board) )
 *      (PP-CLR (IN as) 
 *        (NP (DT a) (JJ nonexecutive) (NN director) ))
 *      (NP-TMP (NNP Nov.) (CD 29) )))
 *  (. .) ))
 * ( (S 
 *   (NP-SBJ (NNP Mr.) (NNP Vinken) )
 *   (VP (VBZ is) 
 *     (NP-PRD 
 *       (NP (NN chairman) )
 *       (PP (IN of) 
 *         (NP 
 *           (NP (NNP Elsevier) (NNP N.V.) )
 *           (, ,) 
 *           (NP (DT the) (NNP Dutch) (VBG publishing) (NN group) )))))
 *   (. .) ))
 *  
 * Code:
 * TBReader tbank = new TBReader("wsj_0001.mrg");
 * TBTree tree;
 *		
 * while ((tree = tbank.nextTree()) != null)
 *	System.out.println(tree.getWords());
 * 
 * Output:
 * Pierre Vinken , 61 years old , will join the board as a nonexecutive director Nov. 29 .
 * Mr. Vinken is chairman of Elsevier N.V. , the Dutch publishing group .
 * </pre>
 * @author Jinho D. Choi
 * <b>Last update:</b> 9/22/2007
 * @see TBTree
 */
public class TBReader
{
	/** Left Round Bracket "(" */
	final public String LRB = "(";
	/** Right Round Bracket ")" */
	final public String RRB = ")";
	private final String HEAD = "TOP";
	private FileTokenizer mb_tok;
	private int mb_numTree;
	private String filename;
	
	/**
	 * Opens a Treebank file 'filename'.
	 * @param filename the Treebank filename.
	 */
	public TBReader(String filename)
	{
		String delim = LRB + RRB + FileTokenizer.WHITE;
		mb_tok = new FileTokenizer(filename, delim, true);
		mb_numTree = 0;
		this.filename = filename;
	}
	
	/** @return (there exists a tree) ? the next tree : null */
	public TBTree nextTree()
	{
		String str;
		
		do
		{
			str = nextToken();
			if (str == null)	return null;
		}
		while(!str.equals(LRB));
		
		int numBracket = 1;
		TBNode head = new TBNode(null, HEAD);	// dummy-head
		TBNode curr = head;						// pointer to the current node
		
		do
		{
			if ((str = nextToken()) == null)
				errorMsg("more token needed");
			
			if (numBracket == 1 && str.equals(HEAD))	continue;
			
			if (str.equals(LRB))
			{
				numBracket++;
				if ((str = nextToken()) == null)		// str = tag
					errorMsg("tag is missing");
				
				TBNode node = new TBNode(curr, str);	// add a child to 'curr'
				curr.addChild(node);
				curr = node;							// move to child
			}
			else if (str.equals(RRB))
			{
				numBracket--;
				curr = curr.getParent();				// move to parent
			}
			else
				curr.setWord(str);						// str = word
		}
		while (numBracket > 0);
		
		mb_numTree++;
	//	TBNode tmp = head.getChildren().get(0);			// omit the dummy head
	//	tmp.setParent(null);
		return new TBTree(head);							
	}
	
	/** @return the current tree number in this file. */
	public int getTreeNumber()
	{
		return mb_numTree;
	}
	
	// skips all white-spaces and returns the next token.
	private String nextToken()
	{
		while (mb_tok.hasMoreTokens())
		{
			String str = mb_tok.nextToken();
			
			if (FileTokenizer.WHITE.indexOf(str) == -1)
				return str;
		}

		return null;
	}
	
	// prints error-message and exits.
	private void errorMsg(String msg)
	{
		System.err.println("error: "+msg+" (line: " + mb_tok.getLineNumber()+", file: "+filename+")");
		System.exit(1);
	}
}
